package com.xunk.system.controller;

import com.xunk.common.core.constant.UserConstants;
import com.xunk.common.core.domain.R;
import com.xunk.common.core.exception.CustomException;
import com.xunk.common.core.utils.DataUtils;
import com.xunk.common.core.utils.StringUtils;
import com.xunk.common.core.utils.ThreadLocalUtils;
import com.xunk.common.core.utils.poi.ExcelUtil;
import com.xunk.common.core.web.controller.BaseController;
import com.xunk.common.core.web.domain.AjaxResult;
import com.xunk.common.core.web.page.TableDataInfo;
import com.xunk.common.log.annotation.Log;
import com.xunk.common.log.enums.BusinessType;
import com.xunk.common.security.utils.SecurityUtils;
import com.xunk.system.api.domain.SysDept;
import com.xunk.system.api.domain.SysRole;
import com.xunk.system.api.domain.SysUser;
import com.xunk.system.api.model.UserDeptInfo;
import com.xunk.system.api.model.UserInfo;
import com.xunk.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/user")
public class SysUserController extends BaseController {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPermissionService permissionService;

    private static final String DEFAULT_AVATAR_URL = "http://120.27.27.46/group1/M00/00/00/CgABWmCvCaGAbT8dAAAj7S0jwTA087.jpg";

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/admin/list")
    public TableDataInfo adminList(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/consume/list")
    public TableDataInfo consumeList(SysUser sysUser) {
        startPage();
        List<SysUser> list = userService.selectConsumeUserList(sysUser);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/admin/export")
    public void exportAdmin(HttpServletResponse response, SysUser user) throws IOException {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "管理员数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/consume/export")
    public void exportConsume(HttpServletResponse response, SysUser user) throws IOException {
        List<SysUser> list = userService.selectConsumeUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = SecurityUtils.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/info/{username}")
    public R<UserInfo> info(@PathVariable("username") String username) {
        SysUser sysUser = userService.selectUserByUserName(username);
        if (StringUtils.isNull(sysUser)) {
            return R.fail("用户名或密码错误");
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser.getUserId());
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser.getUserId());
        UserInfo sysUserVo = new UserInfo();
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        return R.ok(sysUserVo);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        Long userId = SecurityUtils.getUserId();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(userId);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(userId);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", userService.selectUserById(userId));
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            ajax.put(AjaxResult.DATA_TAG, userService.selectUserById(userId));
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return ajax;
    }

    @GetMapping(value = {"/consume"})
    public AjaxResult getConsumeInfo(@RequestParam(value = "userId", required = false) Long userId, @RequestParam(value = "homeId", required = false) Long homeId) {
        try {
            if (DataUtils.isNotEmpty(homeId)) {
                ThreadLocalUtils.put("homeId", homeId);
            }
            return AjaxResult.success(AjaxResult.DATA_TAG, userService.selectUserById(userId));
        } finally {
            ThreadLocalUtils.clear();
        }
    }

    @PostMapping(value = {"/consume"})
    public AjaxResult updateConsumeInfo(@RequestBody SysUser user) {
        return toAjax(userService.updateConsumeUser(user));
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        try {
            doCheck(user);
        } catch (RuntimeException e) {
            return AjaxResult.error(e.getMessage());
        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    //    @PreAuthorize("@ss.hasPermi('system:user:register')")

    /**
     * app用户名就是手机号
     * 昵称也是手机号
     *
     * @param user
     * @return
     */
    @Log(title = "App用户注册", businessType = BusinessType.INSERT)
    @PostMapping("/register")
    public AjaxResult register(@RequestBody SysUser user) {
        try {
            doCheck2(user);
        } catch (RuntimeException e) {
            return AjaxResult.error(e.getMessage());
        }
        user.setPhonenumber(user.getUserName());
        user.setNickName(user.getUserName());
        user.setRoleIds(new Long[]{roleService.selectRoleByRoleKey("home_normal")});
        user.setCreateBy(user.getUserName());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        //  新注册用户给予默认头像
        user.setAvatar(DEFAULT_AVATAR_URL);
        return toAjax(userService.insertUser(user));
    }

    @Log(title = "用户头像上传", businessType = BusinessType.UPDATE)
    @PostMapping("/upload")
    public AjaxResult uploadAvatar(Long userId, MultipartFile file) throws IOException {
        return AjaxResult.success(userService.uploadModelFile(userId, file));
    }

    /**
     * 后台新增用户 或 app注册用户 通用校验规则
     *
     * @param user 用户对象
     */
    private void doCheck(SysUser user) {

        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            throw new RuntimeException("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            throw new RuntimeException("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            throw new RuntimeException("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
    }

    /**
     * App用户名校验
     *
     * @param user
     */
    private static Pattern PHONE_PATTERN = Pattern.compile("^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8}");

    private void doCheck2(SysUser user) {
        if (DataUtils.isEmpty(user.getUserName()) || DataUtils.isEmpty(user.getPassword())) {
            throw new CustomException("新增用户'" + user.getUserName() + "'失败，手机号或者密码不能为空");
        }
        Matcher matcher = PHONE_PATTERN.matcher(user.getUserName());
        if (!matcher.matches()) {
            throw new CustomException("新增用户'" + user.getUserName() + "'失败，手机号格式不正确");
        }
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            throw new RuntimeException("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    @Log(title = "补充用户Dept信息", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/info/dept")
    public R<String> fillInUserInfoToDept(@RequestBody UserDeptInfo info) {
        SysUser sysUser = userService.selectUserByUserName(info.getUsername());
        SysDept dept = new SysDept();
        dept.setDeptId(info.getDeptId());
        dept.setLeader(sysUser.getUserName());
        dept.setPhone(sysUser.getPhonenumber());
        dept.setEmail(sysUser.getEmail());
        deptService.updateDeptLeaderInfo(dept);
        return R.ok();
    }

    @GetMapping("/home")
    public AjaxResult getHomeListInfo() {
        return AjaxResult.success(userService.getHomeListInfo());
    }
}
